package com.keymozy.proxy;

import com.keymozy.annotaion.NoAuthentication;
import com.keymozy.pojo.Staff;
import com.keymozy.state.RespData;
import com.keymozy.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class PowerProxy {
    @Pointcut("execution(* com.keymozy.controller.*.*(..))")
    public void t(){
    }
    @Around("t()")
    public Object test(ProceedingJoinPoint pjp) throws Throwable {
        Staff staff = (Staff) TokenUtil.data.get();
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();
        NoAuthentication annotation = method.getAnnotation(NoAuthentication.class);
//       存在注解noAuthentication不用验证
        if(annotation!=null){
            return pjp.proceed();
        }
        Right right = method.getAnnotation(Right.class);

        if (right == null)
            return pjp.proceed();

        String power = right.power();
        log.info("当前controller的权限:"+power);
        if ("-1".equals(staff.getPosition().getPrivil()) || judgePower(power,staff.getPosition().getPrivil()))
            return pjp.proceed();
        else{
            log.info("权限不足...");
            return new RespData("99999","权限不足...",null);
        }
    }
    public boolean judgePower(String p1,String p2){
        if (p2.contains(p1))
            return true;
        else
            return false;
    }
}
